<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>操作日志 - CRUD Generator</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Common CSS -->
    <link href="/css/common.css" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: #f8f9fa;
            padding-top: 80px;
        }
        
        .navbar {
            background: white !important;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: fixed;
            top: 0;
            width: 100%;
            z-index: 1000;
        }
        
        .main-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .page-header {
            background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
            color: white;
            border-radius: 20px;
            padding: 40px;
            margin-bottom: 30px;
            text-align: center;
        }
        
        .log-filters {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        
        .log-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .log-header {
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 20px 25px;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .log-body {
            padding: 0;
        }
        
        .log-entry {
            border-bottom: 1px solid #e9ecef;
            padding: 20px 25px;
            transition: all 0.3s ease;
            position: relative;
        }
        
        .log-entry:last-child {
            border-bottom: none;
        }
        
        .log-entry:hover {
            background: #f8f9fa;
        }
        
        .log-entry::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 4px;
            background: #e9ecef;
        }
        
        .log-entry.success::before {
            background: #28a745;
        }
        
        .log-entry.warning::before {
            background: #ffc107;
        }
        
        .log-entry.error::before {
            background: #dc3545;
        }
        
        .log-entry.info::before {
            background: #17a2b8;
        }
        
        .log-meta {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 10px;
        }
        
        .log-time {
            font-size: 0.9rem;
            color: #6c757d;
            font-weight: 500;
        }
        
        .log-level {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .level-success {
            background: #d4edda;
            color: #155724;
        }
        
        .level-warning {
            background: #fff3cd;
            color: #856404;
        }
        
        .level-error {
            background: #f8d7da;
            color: #721c24;
        }
        
        .level-info {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .log-title {
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 5px;
        }
        
        .log-description {
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 10px;
        }
        
        .log-details {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            font-family: 'Courier New', monospace;
            font-size: 0.8rem;
            color: #495057;
            margin-top: 10px;
            display: none;
        }
        
        .log-user {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 10px;
        }
        
        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            text-align: center;
        }
        
        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            color: white;
            margin: 0 auto 15px;
        }
        
        .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: #2d3748;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .search-box {
            position: relative;
        }
        
        .search-box .form-control {
            padding-left: 40px;
        }
        
        .search-box .search-icon {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
        }
        
        .filter-tag {
            display: inline-block;
            background: #e9ecef;
            color: #495057;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            margin: 2px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .filter-tag.active {
            background: #667eea;
            color: white;
        }
        
        .filter-tag:hover {
            background: #dee2e6;
        }
        
        .filter-tag.active:hover {
            background: #5a6fd8;
        }
        
        .pagination-wrapper {
            display: flex;
            justify-content: between;
            align-items: center;
            padding: 20px 25px;
            background: #f8f9fa;
            border-top: 1px solid #e9ecef;
        }
        
        .log-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        
        .action-btn {
            padding: 6px 12px;
            border: 1px solid #e9ecef;
            background: white;
            border-radius: 6px;
            color: #6c757d;
            text-decoration: none;
            font-size: 0.8rem;
            transition: all 0.3s ease;
        }
        
        .action-btn:hover {
            background: #f8f9fa;
            color: #495057;
        }
        
        .expand-btn {
            background: none;
            border: none;
            color: #667eea;
            font-size: 0.8rem;
            cursor: pointer;
            padding: 0;
        }
        
        .expand-btn:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <div th:replace="fragments/navigation :: navbar"></div>

    <div class="main-content">
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="display-5 mb-3">
                <i class="bi bi-journal-text me-3"></i>
                操作日志管理
            </h1>
            <p class="lead mb-0">系统操作记录、错误日志和审计追踪</p>
        </div>

        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">
                    <i class="bi bi-check-circle"></i>
                </div>
                <div class="stat-value" id="successCount">1,234</div>
                <div class="stat-label">成功操作</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);">
                    <i class="bi bi-exclamation-triangle"></i>
                </div>
                <div class="stat-value" id="warningCount">56</div>
                <div class="stat-label">警告事件</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #dc3545 0%, #e83e8c 100%);">
                    <i class="bi bi-x-circle"></i>
                </div>
                <div class="stat-value" id="errorCount">12</div>
                <div class="stat-label">错误事件</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #17a2b8 0%, #6f42c1 100%);">
                    <i class="bi bi-info-circle"></i>
                </div>
                <div class="stat-value" id="infoCount">789</div>
                <div class="stat-label">信息记录</div>
            </div>
        </div>

        <!-- Filters -->
        <div class="log-filters">
            <div class="row align-items-center">
                <div class="col-md-4">
                    <div class="search-box">
                        <i class="bi bi-search search-icon"></i>
                        <input type="text" class="form-control" placeholder="搜索日志..." id="searchInput">
                    </div>
                </div>
                <div class="col-md-8">
                    <div class="d-flex flex-wrap align-items-center gap-2">
                        <span class="text-muted me-2">筛选:</span>
                        <span class="filter-tag active" data-level="all">全部</span>
                        <span class="filter-tag" data-level="success">成功</span>
                        <span class="filter-tag" data-level="warning">警告</span>
                        <span class="filter-tag" data-level="error">错误</span>
                        <span class="filter-tag" data-level="info">信息</span>
                        
                        <div class="ms-auto d-flex gap-2">
                            <select class="form-select form-select-sm" style="width: auto;" id="timeRange">
                                <option value="1h">最近1小时</option>
                                <option value="24h" selected>最近24小时</option>
                                <option value="7d">最近7天</option>
                                <option value="30d">最近30天</option>
                            </select>
                            <button class="btn btn-outline-secondary btn-sm" onclick="clearFilters()">
                                <i class="bi bi-x me-1"></i>清除筛选
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Log Entries -->
        <div class="log-card">
            <div class="log-header">
                <h5 class="mb-0">
                    <i class="bi bi-list-ul me-2"></i>操作日志
                </h5>
                <div class="d-flex align-items-center gap-2">
                    <span class="text-muted" id="logCount">显示 1-20 条，共 2,091 条记录</span>
                    <button class="btn btn-outline-primary btn-sm" onclick="toggleAutoRefresh()">
                        <i class="bi bi-arrow-clockwise me-1"></i>
                        <span id="autoRefreshText">开启自动刷新</span>
                    </button>
                </div>
            </div>
            <div class="log-body" id="logEntries">
                <!-- Log entries will be loaded here -->
            </div>
            <div class="pagination-wrapper">
                <div class="d-flex justify-content-between align-items-center w-100">
                    <div>
                        <select class="form-select form-select-sm" style="width: auto;" id="pageSize">
                            <option value="20" selected>每页 20 条</option>
                            <option value="50">每页 50 条</option>
                            <option value="100">每页 100 条</option>
                        </select>
                    </div>
                    <nav>
                        <ul class="pagination pagination-sm mb-0">
                            <li class="page-item disabled">
                                <a class="page-link" href="#" onclick="previousPage()">上一页</a>
                            </li>
                            <li class="page-item active">
                                <a class="page-link" href="#">1</a>
                            </li>
                            <li class="page-item">
                                <a class="page-link" href="#" onclick="goToPage(2)">2</a>
                            </li>
                            <li class="page-item">
                                <a class="page-link" href="#" onclick="goToPage(3)">3</a>
                            </li>
                            <li class="page-item">
                                <a class="page-link" href="#" onclick="nextPage()">下一页</a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Common JS -->
    <script src="/js/common.js"></script>

    <script>
        // Sample log data
        const logData = [
            {
                id: 1,
                timestamp: '2024-01-15 14:30:25',
                level: 'success',
                title: '用户登录成功',
                description: '用户 admin 从 192.168.1.10 成功登录系统',
                user: 'admin',
                module: '用户认证',
                details: {
                    ip: '192.168.1.10',
                    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                    sessionId: 'sess_abc123def456'
                }
            },
            {
                id: 2,
                timestamp: '2024-01-15 14:25:12',
                level: 'info',
                title: '代码生成完成',
                description: '成功为项目 "E-Commerce Platform" 生成 CRUD 代码',
                user: 'developer',
                module: '代码生成器',
                details: {
                    projectName: 'E-Commerce Platform',
                    tables: ['users', 'products', 'orders'],
                    generatedFiles: 15,
                    executionTime: '2.3s'
                }
            },
            {
                id: 3,
                timestamp: '2024-01-15 14:20:45',
                level: 'warning',
                title: '数据库连接超时',
                description: '连接到数据库时发生超时，已自动重试',
                user: 'system',
                module: '数据库',
                details: {
                    database: 'crud_generator_db',
                    timeout: '30s',
                    retryCount: 3,
                    finalStatus: 'success'
                }
            },
            {
                id: 4,
                timestamp: '2024-01-15 14:15:30',
                level: 'error',
                title: '智能合约部署失败',
                description: '数据库连接时发生错误',
                user: 'developer',
                module: '智能合约',
                details: {
                    contractName: 'Contract.sol',
                    network: 'MySQL',
                    error: 'Gas limit exceeded',
                    gasUsed: '2,100,000',
                    gasLimit: '2,000,000'
                }
            },
            {
                id: 5,
                timestamp: '2024-01-15 14:10:15',
                level: 'success',
                title: '系统配置更新',
                description: '管理员更新了数据库连接配置',
                user: 'admin',
                module: '系统设置',
                details: {
                    configType: 'database',
                    changes: ['host', 'port', 'database'],
                    previousHost: '192.168.1.100',
                    newHost: '192.168.1.101'
                }
            },
            {
                id: 6,
                timestamp: '2024-01-15 14:05:22',
                level: 'info',
                title: '数据库连接状态检查',
                description: '定期检查数据库连接状态',
                user: 'system',
                module: '数据库管理',
                details: {
                    network: 'MySQL',
                    status: 'connected',
                    blockHeight: 12345,
                    peers: 4,
                    responseTime: '150ms'
                }
            }
        ];

        let currentPage = 1;
        let pageSize = 20;
        let currentFilter = 'all';
        let searchQuery = '';
        let autoRefreshInterval = null;

        // Initialize page
        document.addEventListener('DOMContentLoaded', function() {
            loadLogs();
            setupEventListeners();
            updateStatistics();
        });

        function setupEventListeners() {
            // Search input
            document.getElementById('searchInput').addEventListener('input', function() {
                searchQuery = this.value;
                loadLogs();
            });

            // Filter tags
            document.querySelectorAll('.filter-tag').forEach(tag => {
                tag.addEventListener('click', function() {
                    document.querySelectorAll('.filter-tag').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    currentFilter = this.dataset.level;
                    loadLogs();
                });
            });

            // Time range
            document.getElementById('timeRange').addEventListener('change', function() {
                loadLogs();
            });

            // Page size
            document.getElementById('pageSize').addEventListener('change', function() {
                pageSize = parseInt(this.value);
                currentPage = 1;
                loadLogs();
            });
        }

        function loadLogs() {
            const container = document.getElementById('logEntries');
            container.innerHTML = '';

            // Filter logs
            let filteredLogs = logData;
            
            if (currentFilter !== 'all') {
                filteredLogs = filteredLogs.filter(log => log.level === currentFilter);
            }
            
            if (searchQuery) {
                filteredLogs = filteredLogs.filter(log => 
                    log.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                    log.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
                    log.user.toLowerCase().includes(searchQuery.toLowerCase())
                );
            }

            // Paginate
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const paginatedLogs = filteredLogs.slice(startIndex, endIndex);

            // Render logs
            paginatedLogs.forEach(log => {
                const logElement = createLogElement(log);
                container.appendChild(logElement);
            });

            // Update count
            document.getElementById('logCount').textContent = 
                `显示 ${startIndex + 1}-${Math.min(endIndex, filteredLogs.length)} 条，共 ${filteredLogs.length} 条记录`;
        }

        function createLogElement(log) {
            const div = document.createElement('div');
            div.className = `log-entry ${log.level}`;
            
            const userInitial = log.user.charAt(0).toUpperCase();
            
            div.innerHTML = `
                <div class="log-meta">
                    <div class="log-time">${log.timestamp}</div>
                    <span class="log-level level-${log.level}">${getLevelText(log.level)}</span>
                </div>
                <div class="log-title">${log.title}</div>
                <div class="log-description">${log.description}</div>
                <div class="log-user">
                    <div class="user-avatar">${userInitial}</div>
                    <div>
                        <strong>${log.user}</strong>
                        <br>
                        <small class="text-muted">${log.module}</small>
                    </div>
                </div>
                <div class="log-actions">
                    <button class="expand-btn" onclick="toggleDetails(${log.id})">
                        <i class="bi bi-chevron-down me-1"></i>查看详情
                    </button>
                    <a href="#" class="action-btn" onclick="copyLog(${log.id})">
                        <i class="bi bi-copy me-1"></i>复制
                    </a>
                    <a href="#" class="action-btn" onclick="shareLog(${log.id})">
                        <i class="bi bi-share me-1"></i>分享
                    </a>
                </div>
                <div class="log-details" id="details-${log.id}">
                    ${formatDetails(log.details)}
                </div>
            `;
            
            return div;
        }

        function getLevelText(level) {
            const levels = {
                success: '成功',
                warning: '警告',
                error: '错误',
                info: '信息'
            };
            return levels[level] || level;
        }

        function formatDetails(details) {
            return Object.entries(details)
                .map(([key, value]) => `${key}: ${JSON.stringify(value)}`)
                .join('\n');
        }

        function toggleDetails(logId) {
            const details = document.getElementById(`details-${logId}`);
            const button = event.target.closest('.expand-btn');
            const icon = button.querySelector('i');
            
            if (details.style.display === 'none' || !details.style.display) {
                details.style.display = 'block';
                icon.className = 'bi bi-chevron-up me-1';
                button.innerHTML = '<i class="bi bi-chevron-up me-1"></i>隐藏详情';
            } else {
                details.style.display = 'none';
                icon.className = 'bi bi-chevron-down me-1';
                button.innerHTML = '<i class="bi bi-chevron-down me-1"></i>查看详情';
            }
        }

        function copyLog(logId) {
            const log = logData.find(l => l.id === logId);
            if (log) {
                const logText = `[${log.timestamp}] ${log.level.toUpperCase()}: ${log.title}\n${log.description}\n用户: ${log.user}\n模块: ${log.module}`;
                Utils.copyToClipboard(logText);
                Utils.showToast('日志已复制到剪贴板', 'success');
            }
        }

        function shareLog(logId) {
            const log = logData.find(l => l.id === logId);
            if (log) {
                const shareUrl = `${window.location.origin}/logs#${logId}`;
                Utils.copyToClipboard(shareUrl);
                Utils.showToast('分享链接已复制到剪贴板', 'success');
            }
        }

        function updateStatistics() {
            const stats = {
                success: logData.filter(log => log.level === 'success').length,
                warning: logData.filter(log => log.level === 'warning').length,
                error: logData.filter(log => log.level === 'error').length,
                info: logData.filter(log => log.level === 'info').length
            };

            // Animate counters
            animateCounter('successCount', stats.success);
            animateCounter('warningCount', stats.warning);
            animateCounter('errorCount', stats.error);
            animateCounter('infoCount', stats.info);
        }

        function animateCounter(elementId, target) {
            const element = document.getElementById(elementId);
            let current = 0;
            const increment = target / 50;
            
            const timer = setInterval(() => {
                current += increment;
                if (current >= target) {
                    current = target;
                    clearInterval(timer);
                }
                element.textContent = Math.floor(current).toLocaleString();
            }, 20);
        }

        function clearFilters() {
            document.getElementById('searchInput').value = '';
            document.getElementById('timeRange').value = '24h';
            document.querySelectorAll('.filter-tag').forEach(tag => tag.classList.remove('active'));
            document.querySelector('.filter-tag[data-level="all"]').classList.add('active');
            
            searchQuery = '';
            currentFilter = 'all';
            currentPage = 1;
            loadLogs();
        }

        function refreshLogs() {
            Utils.showLoading();
            
            setTimeout(() => {
                Utils.hideLoading();
                
                // Simulate new log entries
                const newLog = {
                    id: logData.length + 1,
                    timestamp: new Date().toLocaleString('zh-CN'),
                    level: ['success', 'info', 'warning'][Math.floor(Math.random() * 3)],
                    title: '系统操作',
                    description: '模拟的新日志条目',
                    user: 'system',
                    module: '系统',
                    details: { action: 'refresh', timestamp: Date.now() }
                };
                
                logData.unshift(newLog);
                loadLogs();
                updateStatistics();
                
                Utils.showToast('日志已刷新', 'success');
            }, 1000);
        }

        function exportLogs() {
            Utils.showLoading();
            
            setTimeout(() => {
                Utils.hideLoading();
                
                // Filter logs based on current filters
                let filteredLogs = logData;
                if (currentFilter !== 'all') {
                    filteredLogs = filteredLogs.filter(log => log.level === currentFilter);
                }
                if (searchQuery) {
                    filteredLogs = filteredLogs.filter(log => 
                        log.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                        log.description.toLowerCase().includes(searchQuery.toLowerCase())
                    );
                }
                
                // Create export data
                const exportData = filteredLogs.map(log => ({
                    timestamp: log.timestamp,
                    level: log.level,
                    title: log.title,
                    description: log.description,
                    user: log.user,
                    module: log.module,
                    details: log.details
                }));
                
                // Download as JSON
                const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `operation-logs-${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                Utils.showToast('日志已导出', 'success');
            }, 1500);
        }

        function toggleAutoRefresh() {
            const button = document.getElementById('autoRefreshText');
            
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
                autoRefreshInterval = null;
                button.textContent = '开启自动刷新';
                Utils.showToast('自动刷新已关闭', 'info');
            } else {
                autoRefreshInterval = setInterval(() => {
                    refreshLogs();
                }, 30000); // Refresh every 30 seconds
                button.textContent = '关闭自动刷新';
                Utils.showToast('自动刷新已开启（30秒间隔）', 'success');
            }
        }

        function previousPage() {
            if (currentPage > 1) {
                currentPage--;
                loadLogs();
            }
        }

        function nextPage() {
            currentPage++;
            loadLogs();
        }

        function goToPage(page) {
            currentPage = page;
            loadLogs();
        }
    </script>
</body>
</html>